'''
Created on Nov 4, 2009

@author: wangjo
'''
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
import spider
import logging
import mokomodel
import utility

MAX_PER_PAGE = 50

template.register_template_library('templatefilters')

class IndexPage(utility.BaseRequestHandler):
    def get(self):
        page = self.request.get('page')
        if not page or int(page) < 1:
            page = 1
        else:
            page = int(page)
        logging.info('page: %d'%page)
        offset = (page -1)*MAX_PER_PAGE
        models = mokomodel.topgirl.get_topgirls(MAX_PER_PAGE, offset)
        count = mokomodel.topgirl.get_topgirl_count()
        model_count = mokomodel.model.get_model_count()
        pages = int(count/MAX_PER_PAGE)+1
        self.generate('moko.html', {
                      'application_name' : 'MOKO Top Girl',
                      'models': models,
                      'pages': range(1, pages+1),
                      'page': page,
                      'count': count,
                      'model_count': model_count,
                })
class DispatchPage(utility.BaseRequestHandler):
    _OUTPUT_TYPES = {
            'default': ['text/html', 'html'],
            'html': ['text/html', 'html'],
            'atom': ['application/atom+xml', 'xml'],}
    
    def get(self, action):
        splits = action.split('/')
        t = splits[0].lower()
        if t == u"model":
            if len(splits) < 2: self.error(404)
            items = splits[1].split('?')
            self.modelAction(items[0])
        elif t == 'gallery':
            self.galleryAction()
        elif t == 'photo':
            self.photoAction()
        elif t == 'logphotoload':
            self.logphotoAction()
        elif t == 'avatar':
            self.avatarAction()
        elif t == 'logavatarload':
            self.logavatarAction()
        else:
            self.response.out.write('Action:%s'%t)
    
    def modelAction(self, username):
        action = self.request.get('action')
        if action and action.lower() == 'update':
            m = spider.update_model(username)
        else:
            m = mokomodel.model.get_model(username)
        photos = m.get_photos()
        self.generate('model.html', {'model': m,'photos': photos,})
    
    def galleryAction(self):
        page = self.request.get('page')
        if not page or int(page) < 1:
            page = 1
        else:
            page = int(page)
        logging.info('page: %d'%page)
        offset = (page -1)*MAX_PER_PAGE
        #list all the gallerys
        albums = mokomodel.album.get_albums(MAX_PER_PAGE, offset)
        count = mokomodel.album.get_album_count()
        pages = int(count/MAX_PER_PAGE)+1
        self.generate('gallery.html', {
                      'application_name' : 'MOKO Top Girl',
                      'albums': albums,
                      'pages': range(1, pages+1),
                      'page': page,
                      'count': count,
                })
    
        
    def logphotoAction(self):
        imgkey = self.request.get('imgkey', None)
        if imgkey:
            if imgkey.find('#')>= 0:
                logging.debug('multiple keys:%s'%imgkey)
                keys = imgkey.split('#')
                for key in keys:
                    p = mokomodel.cronlog.add_download_photo(key, True)
            else:
                p = mokomodel.cronlog.add_download_photo(imgkey, True)
            if p:
                self.response.out.write('load image log successful: %s'%p.url)
            else:
                self.response.out.write('load image log failed')
    
    def photoAction(self):
        page = self.request.get('page', 1)
        if not page or int(page) < 1:
            page = 1
        else:
            page = int(page)
        logging.info('page: %d'%page)
        offset = (page -1)*MAX_PER_PAGE
        photos = mokomodel.cronlog.get_non_downloaded_photos(MAX_PER_PAGE, offset)
        if not photos or len(photos) == 0:
            self.error(403)
            return 
        
        output_name = self.request.get('output')
        logging.info('output:%s'%output_name)
        if output_name not in DispatchPage._OUTPUT_TYPES:
            output_name = 'html'
        logging.info('output: %s'%output_name)
        output_type = DispatchPage._OUTPUT_TYPES[output_name]
        if len(photos) > 0:
            updated = max([p.updated for p in photos])
        else:
            updated = None
        lphoto = photos[len(photos)-1]
        self.response.headers['Content-Type'] = output_type[0]
        self.generate('photo_%s.%s' % (output_name, output_type[1]), {
                    'photos': photos,
                    'lphoto': lphoto,
                    'updated': updated,})
    
    def avatarAction(self):
        page = self.request.get('page', 1)
        if not page or int(page) < 1:
            page = 1
        else:
            page = int(page)
        logging.info('page: %d'%page)
        offset = (page -1)*MAX_PER_PAGE
        models = mokomodel.cronlog.get_non_downloaded_avatars(MAX_PER_PAGE, offset)
        if not models or len(models) == 0:
            self.error(403)
            return 
        
        output_name = self.request.get('output')
        logging.info('output:%s'%output_name)
        if output_name not in DispatchPage._OUTPUT_TYPES:
            output_name = 'html'
        logging.info('output: %s'%output_name)
        output_type = DispatchPage._OUTPUT_TYPES[output_name]
        if len(models) > 0:
            updated = max([m.updated for m in models])
        else:
            updated = None
        lmodel = models[len(models)-1]
        self.response.headers['Content-Type'] = output_type[0]
        self.generate('avatar_%s.%s' % (output_name, output_type[1]), {
                    'models': models,
                    'lmodel': lmodel,
                    'updated': updated,})
    
    def logavatarAction(self):
        username = self.request.get('model', None)
        if username:
            p = mokomodel.cronlog.add_download_avatar(username, True)
    
        
application = webapp.WSGIApplication([
            ('/moko', IndexPage),
            (r'/moko/(.*)', DispatchPage)
            ], debug=utility.DEBUG)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()        